package ai.people.core.security.support;

import ai.people.core.security.entity.AuthenticationUser;
import ai.people.netmon.framework.constant.OAuth2Constant;
import ai.people.netmon.framework.domain.ucenter.request.LoginUser;
import ai.people.netmon.framework.exception.enums.AuthExceptionEnum;
import ai.people.netmon.framework.exception.type.AuthException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * 请求持有者
 *
 * @author yuanqinglong
 * @date 2022/2/21 18:13
 */
public class RequestHolderUtil {

    static Logger logger = LoggerFactory.getLogger(RequestHolderUtil.class);


    /**
     * 得到用户id
     *
     * @return {@link Long}
     */
    public static Long getUserId() {
        return loginUser().getUserId();
    }


    /**
     * 登录用户
     *
     * @return {@link LoginUser}
     */
    public static AuthenticationUser loginUser() {
        return (AuthenticationUser) Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication()).map(Authentication::getPrincipal).orElseThrow(() -> new AuthException(AuthExceptionEnum.UNAUTHORIZED_ACCESS));
    }


    /**
     * 查看是否拥有某项权限
     *
     * @param permission 权限
     * @return boolean
     */
    public static boolean hasPermission(String permission) {
        return Optional.ofNullable(loginUser().getAuthorities()).map(grantedAuthorities -> grantedAuthorities.contains(new SimpleGrantedAuthority(permission))).orElse(false);
    }


    /**
     * 查看是否拥有某角色
     *
     * @param roleCode 角色代码
     * @return boolean
     */
    public static boolean hasRole(String roleCode) {
        return Optional.ofNullable(loginUser().getAuthorities()).map(grantedAuthorities -> grantedAuthorities.contains(new SimpleGrantedAuthority(OAuth2Constant.DEFAULT_ROLE_PREFIX + roleCode))).orElse(false);
    }

}
